package com.ufpr.bean;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;

import br.com.sebrae.pr.sgp.entities.Usuario;
import br.com.sebrae.pr.sgp.services.UsuarioServiceRemote;
import br.com.sebrae.pr.sgp.services.impl.UsuarioServiceImpl;
import br.com.sebrae.pr.sgp.util.MD5;

@RequestScoped
@ManagedBean(name = "usuarioManagedBean")
public class UsuarioManagedBean extends GenericManagedBean {
	
	@EJB(name = "UsuarioServiceImpl")
    private UsuarioServiceRemote usuarioServiceRemote = new UsuarioServiceImpl();
	
//	UserService userService = new UserService();

	// fields
	private String username;
	private String password;
	
	
	
	public UsuarioManagedBean() {
	    super();
	    System.out.println("construtor UsuarioManagedBean");
    }
	
	@PostConstruct public void init()
	{ 
		System.out.println(" Bean executado! "); 
	}


	// getters
	public String getUsername() {
		return "username";
	}
	public String getPassword() {
		return password;
	}


	// setters
	public void setUsername(String username) {
		this.username = username;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setUsuarioLogado(Usuario usuario) {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
		if (session != null)
			session.setAttribute("usuarioLogado", usuario);
	}

	// public methods
	public String login() {
		FacesContext context = FacesContext.getCurrentInstance();
		try {
			final Usuario usuario = usuarioServiceRemote.pesquisarPorLoginSenha(getUsername(), MD5.encode(getPassword()));
//			Usuario usuario = UsuarioDAO.getUsuario(getUsername(), getPassword());
			if (usuario == null) {
				context.addMessage("username", new FacesMessage("Usuário e/ou senha inválidos"));
				return null;
			}
			setUsuarioLogado(usuario);
			return "consertos";
		} catch (Exception e) {
			context.addMessage("username", new FacesMessage("Erro ao realizar login no sistema"));
			e.printStackTrace();
			return null;
		}
	}
	public String limpar() {
		this.username = "";
		password = "";
		return null;
	}
	public String logout() {
		setUsuarioLogado(null);		
		FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
		return "login";
	}
	
	public void buttonAction(ActionEvent actionEvent) {
        addMessage("Welcome to Primefaces!!");
    }
     
    public void addMessage(String summary) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary,  null);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
}